package cn.ss.exam2302.service.impl;

import cn.ss.exam2302.entity.Answer;
import cn.ss.exam2302.entity.User;
import cn.ss.exam2302.mapper.AnswerMapper;
import cn.ss.exam2302.service.AnswerService;
import cn.ss.exam2302.util.EncryptUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class AnswerServiceImpl implements AnswerService {
    @Autowired
    private AnswerMapper answerMapper;

    @Override
    public void answer(Integer paId, Integer pos, Character ansSelect) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getUsrId();
        QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.eq("ans_usr_id", userId);
        answerQueryWrapper.eq("ans_pa_id", paId);
        answerQueryWrapper.eq("ans_pos", pos);
        Answer answer = answerMapper.selectOne(answerQueryWrapper);
        if (answer != null) {
            answer.setAnsSelect(ansSelect);
            answer.setAnsUpdatedate(new Date());
            answerMapper.updateById(answer);
            return;
        }
        answer = new Answer();
        answer.setAnsId(EncryptUtil.randUUID());
        answer.setAnsUsrId(userId);
        answer.setAnsPaId(paId);
        answer.setAnsPos(pos);
        answer.setAnsSelect(ansSelect);
        answer.setAnsCreatedate(new Date());
        answerMapper.insert(answer);
    }
}
